package com.example.service;

import cn.hutool.core.date.DateUtil;
import com.example.entity.Busorders;
import com.example.entity.Busticket;
import com.example.exception.CustomException;
import com.example.mapper.BusticketMapper;
import com.example.utils.TimeUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 汽车信息表业务处理
 **/
@Service
public class BusticketService {

    @Resource
    private BusticketMapper busticketMapper;

    /**
     * 新增
     */
    public void add(Busticket busticket) {
        busticketMapper.insert(busticket);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        busticketMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            busticketMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(Busticket busticket) {
        busticketMapper.updateById(busticket);
    }

    /**
     * 根据ID查询
     */
    public Busticket selectById(Integer id) {
        return busticketMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<Busticket> selectAll(Busticket busticket) {
        return busticketMapper.selectAll(busticket);
    }

    /**
     * 分页查询
     */
    public PageInfo<Busticket> selectPage(Busticket busticket, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Busticket> list = busticketMapper.selectAll(busticket);
        return PageInfo.of(list);
    }

    /**
     * 获取跟当前车次匹配的可改签的车次
     */
    public List<Busticket> getChange(Busorders busorders) throws ParseException {
        // 1. 判断当前的时间是否已经过了发车的时间
        String now = DateUtil.now();
        String flyTime = busorders.getFlyTime();
        if (!TimeUtils.compareDate(flyTime, now, "yyyy-MM-dd HH:mm:ss")) {
            throw new CustomException("-1", "您的车次已发车，无法改签");
        }
        // 查询出待改签的车次
        Integer ticketId = busorders.getTicketId();
        Busticket busticket = busticketMapper.selectById(ticketId);
        // 查询所有的车次
        List<Busticket> bustickets = busticketMapper.selectAll(new Busticket());
        // 筛选可改签的车次
        return bustickets.stream()
                .filter(x -> x.getStartCity().equals(busticket.getStartCity())
                        && x.getEndCity().equals(busticket.getEndCity())
                        && x.getNum() >= busorders.getNum()
                        && !x.getId().equals(ticketId))
                .collect(Collectors.toList());
    }
}